package com.dawn.utils;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class CalculateTime {

	static private final long second = 1000;
	static private final long minitue = 60 * 1000;
	static private final long hour = 60 * minitue;
	static private final long day = hour * 24;
	static private final long month = 30 * day;
	static private final long year = 365 * month;
	static private final String format = "yyyy-MM-dd HH:mm:ss";

	private static SimpleDateFormat dateFormat = new SimpleDateFormat(format);

	private Calendar datetime;
	private Date utildate;
	private Calendar calendarNow = Calendar.getInstance();
	private Date utilNow = new Date();
	private String dateString;

	private void setUtildate(Date datetime) {
		this.utildate = datetime;
	}

	private void setDatetime(Calendar datetime) {
		this.datetime = datetime;
	}

	private String getDateString() {
		long interval = 0, datelong = 0;
		if (this.utildate != null) {
			datelong = this.utildate.getTime();
			long nowlong = utilNow.getTime();
			interval = nowlong - datelong;
		} else {
			datelong = datetime.getTimeInMillis();
			long nowlong = calendarNow.getTimeInMillis();
			interval = nowlong - datelong;
		}
		if (interval >= year) {
			dateString = "" + interval / year + "年前";
		} else if (interval >= month) {
			dateString = "" + interval / month + "月前";

		} else if (interval >= day) {
			dateString = "" + interval / day + "天前";
		} else if (interval >= hour) {
			dateString = "" + interval / hour + "小时前";
		} else if (interval >= minitue) {
			dateString = "" + interval / minitue + "分钟前";
		} else if (interval >= second) {
			dateString = "" + interval / 1000 + "秒前";
		} else if (interval < 0) {
			Date ddd = new Date(datelong);
			SimpleDateFormat df = new SimpleDateFormat("yyyy年MM月dd日");
			dateString = df.format(ddd);
		}
		return dateString;
	}

	public static String getDateString(Calendar datetime) {
		CalculateTime ct = new CalculateTime();
		ct.setDatetime(datetime);
		return ct.getDateString();
	}

	public String getDateStringLocalized() {
		SimpleDateFormat df = new SimpleDateFormat("yyyy年MM月dd日");
		return df.format(datetime.getTime());
	}

	public static String getDateStringLocalized(Calendar datetime) {
		SimpleDateFormat df = new SimpleDateFormat("yyyy年MM月dd日");
		return df.format(datetime.getTime());
	}

	public static String getDateStringStandard(Calendar datetime) {
		SimpleDateFormat df = new SimpleDateFormat();
		return df.format(datetime.getTime());
	}

	public static String getDateStringForSql(Calendar datetime) {
		return dateFormat.format(datetime.getTime());
	}
}
